package com.practice.service.impl;

import com.practice.constants.Constants;
import com.practice.ex.ServiceErrorCode;
import com.practice.ex.ServiceException;
import com.practice.utils.MyIdGenerator;
import com.practice.mapper.UserMapper;
import com.practice.pojo.entity.User;
import com.practice.pojo.vo.UserVO;
import com.practice.security.UserDetail;
import com.practice.service.UserService;
import com.practice.utils.SecurityUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO your comment
 *
 * @author Masiyu
 * @date 2023/9/22 16:29
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Value("${practice.jwt.secret-key}")
    String secretKey;
    
    @Value("${practice.jwt.duration-in-minute}")
    Integer date;
    
    @Autowired
    UserMapper userDao;
    
    @Autowired
    AuthenticationManager authenticationManager;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private MyIdGenerator idGenerator;
    @Override
    public List<User> findAll() {
        Long userId = SecurityUtils.getLoginInfo().getId();
        log.debug("登录人ID:{}",userId);
        return userDao.findAll(null);
    }
    
    @Override
    public void add(User user) {
        List<User> resultList = userDao.findAll(null);
        for (User result : resultList) {
            if (result.getName().equals(user.getName())){
                throw new ServiceException(ServiceErrorCode.WARN_USER_EXIST,"用户已存在");
            }
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        Date current = new Date();
        user.setUpdateTime(current);
        user.setCreateTime(current);
        
        user.setStatus(Constants.USER_NORMAL);
        user.setId(idGenerator.snowflakeId());
        userDao.add(user);
    }
    
    @Override
    public String login(String name, String pw , String pass) {
        log.debug("----------------------开始处理登录---------------------");
        Authentication result = null;
        if (pass!=null && pass.equals("true")){
             result = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(name, Constants.DEFAULT_PASSWORD));
        }else {
             result = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(name, pw));
        }
      
        //将通过认证的用户相关信息存入到JWT中
        UserDetail userDetail = (UserDetail) result.getPrincipal();
        //过期时间
        Date time = new Date(System.currentTimeMillis() + date * 60 * 1000);
        Map<String,Object> infos = new HashMap<>();
        infos.put("id",userDetail.getId());
        infos.put("name",userDetail.getUsername());
        infos.put("state",userDetail.getState());
        return Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setClaims(infos)
                .setExpiration(time)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }
    
    @Override
    public UserVO getCurrentUser() {
        Long userId = SecurityUtils.getLoginInfo().getId();
        User user = userDao.findById(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }
}
